/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gps.autocomplete;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import javax.el.ELContext;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import system.general.Exc;
import system.general.Logged;
import system.general.Message;
import system.general.Persistencia;

/**
 *
 * @author emojica
 */
@ManagedBean(name = "gps_autoCompleteFind")
@FacesConverter(value = "gps_autoCompleteFind")
@RequestScoped
public class Find implements Converter {

    Logged logged;
    private Persistencia persistencia = new Persistencia();
    private Beans selectedBean = new Beans();
    private String sql = "";
    private String command = "SELECT * FROM public.v_gps g WHERE ";
    private String order = "ORDER BY g.nombre";
    private Message msg = new Message();

    public Find() {
        ELContext elContext = FacesContext.getCurrentInstance().getELContext();
        logged = (Logged) FacesContext.getCurrentInstance().getApplication().getELResolver().getValue(elContext, null, "logged");
    }

    public Beans getSelected() {
        return selectedBean;
    }

    public void setSelected(Beans bean) {
        if (bean != null) {
            logged.setMasterId(selectedBean.getGeneralBeans().getId());
        }
    }

    public boolean byExist(Map map) throws Exc, SQLException, Exception {
        List<Beans> listBean = byMap(map);
        if (listBean.isEmpty()) {
            listBean.clear();
            return false;
        }
        listBean.clear();
        return true;
    }

    public List<Beans> autoComplete(String data) throws Exc, SQLException, Exception {
        try {
            data = data.replace(" ", "|");
            Map<String, String> map = new LinkedHashMap<>();
            if (logged.getLoggedRol() == 2) {
                map.put("g.id   IN ( select id_gps from  public.v_compania_gps where id_compania=" + logged.getDetailId(), " ) AND  ( ");
            }
            map.put("lower(g.nombre) SIMILAR TO '%(" + strChar(data) + ")%'", " OR ");
            map.put("lower(g.marca) SIMILAR TO '%(" + strChar(data) + ")%'", " OR ");
            map.put("lower(g.imei)SIMILAR TO '%(" + strChar(data) + ")%'", " ");

            if (logged.getLoggedRol() == 2) {
                map.put(" ) ", " ");
            }
            return byMap(map);
        } catch (Exc ex) {
            msg.showMsg(namePackage(), "system", ex.getIdError());
        } catch (SQLException ex) {
            msg.showErr(namePackage(), "sql", ex);
        } catch (Exception ex) {
            msg.showErr(namePackage(), "java", ex);
        } finally {
        }
        return byMap(null);
    }

    public List<Beans> byMap(Map map) throws Exc, SQLException, Exception {
        Iterator it = map.entrySet().iterator();
        StringBuilder criteria = new StringBuilder("");
        while (it.hasNext()) {
            Map.Entry e = (Map.Entry) it.next();
            criteria.append(e.getKey().toString());
            criteria.append(e.getValue().toString());
        }
        sql = command + criteria + order;
        return executeSql(sql);
    }

    private List<Beans> executeSql(String sql) throws Exc, SQLException, Exception {
        List<Beans> listBean = new ArrayList<>();
        ResultSet rsts = persistencia.executeRsts(sql);
        while (rsts.next()) {
            Beans beans = new Beans(
                    rsts.getInt("id"),
                    rsts.getString("imei"),
                    rsts.getString("numero_serie"),
                    rsts.getString("marca"),
                    rsts.getString("modelo"),
                    rsts.getString("nombre"),
                    rsts.getInt("tipo"),
                    rsts.getString("detalle"),
                    rsts.getTimestamp("caducidad"));
            listBean.add(beans);
        }
        //Desconecta de la base de datos debido a que es un resultset y podria quedar la conexion activa
        persistencia.dbDisconnect();
        return listBean;
    }

    private String strChar(String data) {
        data = data.toLowerCase().trim();
        data = data.replaceAll("á", "a");
        data = data.replaceAll("é", "e");
        data = data.replaceAll("í", "i");
        data = data.replaceAll("ó", "o");
        data = data.replaceAll("ú", "u");
        data = data.replaceAll("a", "[a,á]");
        data = data.replaceAll("e", "[e,é]");
        data = data.replaceAll("i", "[i,í]");
        data = data.replaceAll("o", "[o,ó]");
        data = data.replaceAll("u", "[u,ú]");
        return data;
    }

    private String namePackage() {
        Package pack = this.getClass().getPackage();
        return pack.getName();
    }

    public boolean acceso() {
        if (logged.getLoggedRol() == 1 | logged.getLoggedRol() == 2) {
            return true;
        }
        return false;

    }

    @Override
    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("0")) {
            return null;
        }
        int id = Integer.parseInt(submittedValue.substring(0, submittedValue.indexOf("-")));
        String name = submittedValue.substring(submittedValue.indexOf("-") + 1, submittedValue.length());
        logged.setMasterId(id);
        logged.setMasterName(name);
        return null;
    }

    @Override
    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (((Beans) value).getGeneralBeans().getId() == 0) {
            return "";
        }
        return String.valueOf(((Beans) value).getGeneralBeans().getId()) + "-" + ((Beans) value).getGeneralBeans().getNombre();
    }
}
